package com.ly.mp.busicen.rule.field;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import com.ly.mp.busicen.rule.IRuleReload;
import com.ly.mp.busicen.rule.config.XruleConfig;
import com.ly.mp.busicen.rule.config.XruleExtendCfg;
import com.ly.mp.busicen.rule.field.article.FieldArticleContainer;
import com.ly.mp.busicen.rule.field.article.ext.FieldArticle;
import com.ly.mp.busicen.rule.field.msg.FieldMsgContainer;
import com.ly.mp.busicen.rule.field.msg.ext.FieldMsg;
import com.ly.mp.busicen.rule.field.validator.ValidatorBase;
import com.ly.mp.busicen.rule.field.validator.ValidatorContainer;

@Configuration
@ComponentScan("com.ly.mp.busicen.rule.field.validator.plugin")
public class FiledRuleLoader implements IRuleReload, ApplicationContextAware {

	ApplicationContext application;

	@Autowired
	ValidatorContainer validatorContainer;

	@Autowired
	FieldArticleContainer fieldArticleContainer;

	@Autowired
	FieldMsgContainer fieldMsgContainer;

//	@Autowired(required = false)
//	MongoTemplate mongoTemplate;
	
	@Autowired()
	NamedParameterJdbcTemplate jdbcTemplate;
	
	@Autowired
	XruleConfig xruleConfig;
	
//	@Bean
//	@ConditionalOnMissingBean
//	public NamedParameterJdbcTemplate NamedParameterJdbcTemplate(DataSource dataSource) {
//		return new NamedParameterJdbcTemplate(dataSource);
//	}

	@PostConstruct
	public void load() {		
		validatorLoad();
		xruleConfig.xruleDataLoadCfg().fieldLoading().loading(this,this::articleLoad);
		xruleConfig.xruleDataLoadCfg().messageLoading().loading(this,this::msgLoad);		
	}

	@Override
	public boolean reload() {
		load();
		return false;
	}

	public void validatorLoad() {
		Map<String, ValidatorBase> beans = application.getBeansOfType(ValidatorBase.class);
		Map<String, ValidatorBase> validators = new HashMap<String, ValidatorBase>();
		beans.values().forEach(m -> {
			validators.put(m.validName(), m);
		});
		validatorContainer.setValidators(validators);
	}

	public void articleLoad() {
		fieldArticleContainer.setArticles(loadArticleInDb());
		if(xruleConfig.xruleExtendCfg().currentCustMode()) {
			fieldArticleContainer.setArticlesCust(loadArticleInDbCust());
		}
		fieldArticleContainer.cleanCache();
	}
	
	Map<String, Object> null2Empty(Map<String, Object> map){
		map.forEach((k,v)->{
			if (v==null) {
				map.put(k, "");
			}
		});
		return map;
	}
	
	// t_prc_db_sence_validatecolum
	public List<FieldArticle> loadArticleInDb(){
		List<FieldArticle> list = null;
		String sql = "SELECT CONCAT(c.BUSINESSFLOW_SENCECODE,c.DATA_TYPE) as FUNC,c.COLUM_CODE,c.CAR_BRAND_CODE,c.COLUM_NAME,c.OEM_CODE,c.VALIDATE_CONTENT " + 
				"from "+xruleConfig.xruleDataCfg().fieldRule()+" c where c.IS_ENABLE='1'";
		List<Map<String, Object>> results = jdbcTemplate.queryForList(sql, new HashMap<String, Object>());
		list = results.stream().map(m->{
			null2Empty(m);
			FieldArticle fieldArticle = new FieldArticle();
			fieldArticle.setColumn(m.get("COLUM_CODE").toString());
			fieldArticle.setColumnBrand(m.get("CAR_BRAND_CODE").toString());
			fieldArticle.setColumnName(m.get("COLUM_NAME").toString());
			fieldArticle.setColumnOem(m.get("OEM_CODE").toString());
			fieldArticle.setValidContent(m.get("VALIDATE_CONTENT").toString());			
			fieldArticle.setFunction(m.get("FUNC").toString());
			return fieldArticle;
			}).collect(Collectors.toList());
		return list;
	}
	
	public List<FieldArticle> loadArticleInDbCust(){
		List<FieldArticle> list = null;
		String sql = "SELECT CONCAT(c.BUSINESSFLOW_SENCECODE,c.DATA_TYPE) as FUNC,c.COLUM_CODE,c.CAR_BRAND_CODE,c.COLUM_NAME,c.OEM_CODE,c.VALIDATE_CONTENT " + 
				"from "+xruleConfig.xruleDataCfg().fieldRule()+XruleExtendCfg.CUST_EXT+" c where c.IS_ENABLE='1'";
		List<Map<String, Object>> results = jdbcTemplate.queryForList(sql, new HashMap<String, Object>());
		list = results.stream().map(m->{
			null2Empty(m);
			FieldArticle fieldArticle = new FieldArticle();
			fieldArticle.setColumn(m.get("COLUM_CODE").toString());
			fieldArticle.setColumnBrand(m.get("CAR_BRAND_CODE").toString());
			fieldArticle.setColumnName(m.get("COLUM_NAME").toString());
			fieldArticle.setColumnOem(m.get("OEM_CODE").toString());
			fieldArticle.setValidContent(m.get("VALIDATE_CONTENT").toString());			
			fieldArticle.setFunction(m.get("FUNC").toString());
			return fieldArticle;
			}).collect(Collectors.toList());
		return list;
	}	

	public void msgLoad() {
		fieldMsgContainer.setFieldMsgs(loadMsgInDb());
	}
	
	// t_prc_db_log_model
	public List<FieldMsg>  loadMsgInDb(){
		List<FieldMsg> result = new ArrayList<FieldMsg>();
		String sql = "SELECT * from "+xruleConfig.xruleDataCfg().messageRule()+" t where t.IS_ENABLE = '1'";
		List<Map<String, Object>> results = jdbcTemplate.queryForList(sql, new HashMap<String, Object>());
		result = results.stream().map(m->{
			null2Empty(m);
        	FieldMsg fieldMsg = new FieldMsg();
        	fieldMsg.setBrandCode(m.get("CAR_BRAND_CODE").toString());
        	fieldMsg.setMessageId(m.get("LOG_ID").toString());
        	fieldMsg.setMessageTitle(m.get("LOG_MSG").toString());
        	fieldMsg.setOemCode(m.get("OEM_CODE").toString());
        	return fieldMsg;
        }).collect(Collectors.toList());
		return result;
	}
	

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		application = applicationContext;
	}

	

}
